import datetime
import hashlib
import random


def get_md5(origin_str):
    md5_str = hashlib.md5(origin_str.encode(encoding='utf-8')).hexdigest()
    return md5_str


def get_timestamp(time_val=None):
    if time_val is None:
        time_val = datetime.datetime.now().timestamp()

    return int(round(time_val * 1000))


def get_auth_token(id_str):
    return get_md5(str(get_timestamp()) + '_' + id_str)


def get_pwd_salt(c_num):
    salt_str = ''
    for i in range(c_num):
        salt_str += random.choice([chr(random.randint(48, 57)), chr(random.randint(97, 122))])
    return salt_str

def get_username(c_num):
    username = ''
    for i in range(c_num):
        username += chr(random.randint(97, 122))
    return username

def get_score(c_num):
    score = ''
    for i in range(c_num):
        score += chr(random.randint(48, 57))
    return score

"""
校验密码是否正确
:param pwd_str: 原始密码
:param salt: 随机盐
:param md5_str: 数据库加密后的密码串
:return: True-正确，False-错误
"""
def check_pwd(pwd_str, salt, md5_str):
    check_str = get_md5(pwd_str + salt)
    return check_str == md5_str

"""
返回一次最后一次修改时间
:param time_list: 一个数组时间
:return: 一次最近当前时间的时间
"""

def latest_time(time_list):
    test_time = datetime.datetime.now()
    for i in range(len(time_list)):
        for j in range(i+1, len(time_list)):
            if time_list[i] < time_list[j]:
                test_time = time_list[j]

    return test_time